package com.formula.distribution.lock.lock;

import com.formula.distribution.lock.entity.LockInfo;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author:bo
 * @email:
 * @date 2018/12/26
 * @introduce
 **/
public class WriteLock implements LockInterface {
    private static volatile RReadWriteLock rReadWriteLock;


    private final LockInfo lockInfo;


    private RedissonClient redissonClient;


    public WriteLock(LockInfo lockInfo, RedissonClient redissonClient) {
        this.lockInfo = lockInfo;
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean acquire() {
        try {
            rReadWriteLock = redissonClient.getReadWriteLock(lockInfo.getName());
            return rReadWriteLock.writeLock().tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void release() {
        if (rReadWriteLock.writeLock().isHeldByCurrentThread()) {
            rReadWriteLock.writeLock().unlinkAsync();
        }
    }
}
